<template>
  <div class="flex">
    <div class="app-container" style="width: 75%;">
      <!--工具栏-->
      <div class="head-container">

        <div v-if="crud.props.searchToggle">
          <!-- 搜索 -->
          <el-form label-width="70px" size="small" v-formkey="{query:crud.toQuery}">
            <el-row :gutter="10">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-form-item label="开始月份">
                  <el-date-picker
                    v-model="startDate"
                    type="month"
                    size="small"
                    class="date-item"
                    style="width: 100%;"
                    format="yyyy - M"
                    value-format="yyyy-M" @change="changeStartDate"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-form-item label="结束月份">
                  <el-date-picker
                    v-model="endDate"
                    type="month"
                    size="small"
                    class="date-item"
                    style="width: 100%;"
                    format="yyyy - M"
                    value-format="yyyy-M" @change="changeEndDate"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-form-item label="部门">
                  <treeselect
                    v-model="query.deptIds"
                    :options="deptList"
                    placeholder="请选择部门"
                    style="width: 100%"
                    :normalizer="normalizer"
                    @input="val=>getNoStr(val,'deptList','deptIds')"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-form-item label="人员">
                  <zSelect :value.sync="query.userIds"  url="api/dropDown/sysUserList" :params="{deptId:query.deptId}" style="width:  100%"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-form-item label="班次">
                  <zSelect :value.sync="query.scheduleIds" url="/api/dropDown/basScheduleList" style="width:  100%"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <rrOperation :crud="crud"/>
        </div>
        <crudOperation :permission="permission">
          <el-button
            :loading="crud.downloadLoading"
            class="filter-item"
            size="mini"
            slot="left"
            type="warning"
            @click="toExportDetail"
          >导出详情</el-button>
        </crudOperation>
      </div>
      <!-- 表单渲染 -->
      <div class="body-container">
        <!--表格渲染-->

        <el-table ref="table"  border
                  height="700"
                  show-summary
                  v-loading="crud.loading"
                  :data="crud.data"
                  size="small"
                  style="width: 100%;"
                  :summary-method="crud.sumRow"
                  @row-click="crud.selectRow"
                  :row-style="crud.rowClass"
                  :row-class-name="crud.tableRowClassName"
                  @selection-change="crud.selectionChangeHandler"
                  @row-dblclick="jump('kaoqClassesDetail',$event)">
          <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
          <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('deptName')" prop="deptName" label="部门" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('userName')" prop="userName" label="人员" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('scheduleName')" prop="scheduleName" label="班次" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('laterCount')" prop="laterCount" label="迟到次数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('earlierCount')" prop="earlierCount" label="早退次数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('missCount')" prop="missCount" label="漏打卡次数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('overtimeDaySum')" prop="overtimeDaySum" label="加班天数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('missionLeaveDaySum')" prop="missionLeaveDaySum" label="公出天数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('vacationLeaveDaySum')" prop="vacationLeaveDaySum" label="年假天数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('leaveDaySum')" prop="leaveDaySum" label="合计请假" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('presentDaySum')" prop="ok" label="正常天数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('absentDaySum')" prop="error" label="异常天数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('laterSignCount')" prop="laterSignCount" label="补卡次数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('checkedCount')" prop="checkedCount" label="查岗次数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('meetingCount')" prop="meetingCount" label="会议次数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('checkedCount')" prop="squatPointCount" label="蹲点次数" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('meetingCount')" prop="unfamiliarCustomerVisitCount" label="陌拜次数" />
        </el-table>
        <!--分页组件-->
        <pagination/>
      </div>
    </div>
    <div class="rightBox" style="width: 25%;height: 100%">
      <div style="height: 30px;"/>
      <div>
        <div class="label">上下班打卡</div>
        <div style="font-size: 18px;margin-bottom: 20px">正常人数:{{ crud.summary.ok }}人 异常人数:{{ crud.summary.error }}</div>
        <div class="flex content">
          <div class="fl1">
            <div class="flex a-item j-content">{{ crud.summary.laterCount }}</div>
            <div class="flex a-item j-content">迟到人数</div>
          </div>
          <div class="fl1">
            <div class="flex a-item j-content">{{ crud.summary.missCount }}</div>
            <div class="flex a-item j-content">缺卡</div>
          </div>
          <div class="fl1">
            <div class="flex a-item j-content">{{ crud.summary.earlierCount }}</div>
            <div class="flex a-item j-content">早退</div>
          </div>
          <div class="fl1">
            <div class="flex a-item j-content">{{ crud.summary.absentCount }}</div>
            <div class="flex a-item j-content">旷工</div>
          </div>
          <div class="fl1">
            <div class="flex a-item j-content">{{ crud.summary.laterSignCount }}</div>
            <div class="flex a-item j-content">补卡</div>
          </div>
        </div>
      </div>
      <div style="height: 30px;"/>
      <div>
        <div class="label">假勤</div>
        <div class="flex content">
          <div style="width: 20%">
            <div class="flex a-item j-content">{{ crud.summary.leaveCount }}</div>
            <div class="flex a-item j-content">请假</div>
          </div>
          <div style="width: 20%">
            <div class="flex a-item j-content">{{ crud.summary.earlierCount }}</div>
            <div class="flex a-item j-content">出差</div>
          </div>
        </div>
      </div>
      <div style="height: 30px;"/>
      <div>
        <div class="label">加班</div>
        <div class="flex content">
          <div style="width: 20%">
            <div class="flex a-item j-content">{{ crud.summary.overtimeCount }}</div>
            <div class="flex a-item j-content">请假</div>
          </div>
        </div>
      </div>
      <div style="height: 30px;"/>
      <div>
        <div class="label">蹲点</div>
        <div class="flex content">
          <div style="width: 20%">
            <div class="flex a-item j-content">{{ crud.summary.squatPointCount }}</div>
            <div class="flex a-item j-content">蹲点</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import crudBasGoods from '@/api/erp/classesIndex'
  import CRUD, {crud, form, header, presenter} from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'
  import {getDepts} from "@/api/system/dept";
  import Treeselect from '@riophae/vue-treeselect'
  import { download } from '../../../../api/data'
  import { downloadFile } from '../../../../utils'
  let thisDate = new Date().getFullYear() +'-'+ (new Date().getMonth() + 1)
  // crud交由presenter持有
  const defaultCrud = CRUD({
    title: '考勤记录', url: '/api/reportAttendance', sort: 'id,desc',
    query:{
          startYear:thisDate.split('-')[0],
          startMonth:thisDate.split('-')[1],
          endYear:thisDate.split('-')[0],
          endMonth:thisDate.split('-')[1],
        },
      crudMethod: {...crudBasGoods},
      optShow: {
      add: false,
      edit: false,
      del: false,
    },
    props:{
      tableColumns:[
        'name',
        'code'
      ]
    }
  });
  const defaultForm = {
  };
  export default {
    name: 'kaoqClasses',
    components: {pagination, crudOperation, rrOperation, udOperation,Treeselect},
    mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
    dicts: ['t_bas_goods_type', 'common_status', 't_bas_goods_buy_sale_type', 'common_yes_or_no',
      't_bas_goods_price_type', 't_bas_goods_expiration_unit', 't_bas_goods_level', 't_bas_goods_source_type'],
    data() {
      return {
        multiple:true,
        dateScopes:[{//星期选择
          label:'星期一',value:'1'},{
          label:'星期二',value:'2'},{
          label:'星期三',value:'3'},{
          label:'星期四',value:'4'},{
          label:'星期五',value:'5'},{
          label:'星期六',value:'6'},{
          label:'星期天',value:'0'}],
        permission: {
          //add 不添加权限，这个add按钮自定义
          add: ['admin'],
          edit: ['admin', 'basGoods:edit'],
          del: ['admin', 'basGoods:del'],
          enable: ['admin', 'basGoods:enable'],
          disable: ['admin', 'basGoods:disable'],
        },
        rules: {},
        date:thisDate,
        startDate:thisDate,
        endDate:thisDate,
        deptList:[]
      }
    },
    watch: {
      },

    updated() {
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })},
    created() {
      this.getdeptList()
    },
    methods: {
      changeEndDate(val){
        this.query.endYear= val.substr(0,4)
        this.query.endMonth= val.substr(5,2)
      },
      changeStartDate(val){
        this.query.startYear= val.substr(0,4)
        this.query.startMonth= val.substr(5,2)
      },
      jump(url, e) {
        this.$router.push({ path: `${url}/${e.userId}`,
        query:{
          startYear:this.query.startYear,
          startMonth:this.query.startMonth,
          endYear:this.query.endYear,
          endMonth:this.query.endMonth,
        }
    }
      );
    },
      getdeptList() {
        getDepts({status: 1}).then(res => {
      this.deptList = res
    })
    },
      getNoStr(val, type, prop) {
      let str = "";
      val.forEach((item) => {
        const itemNode = this.getTreeName(this[type], item);
        str = this.getNode(itemNode, str);
      });
      this.query[prop] = str;
    },
    getTreeName(treeList, id) {
      let _this = this;
      for (let i = 0; i < treeList.length; i++) {
        let treeItem = treeList[i];
        if (treeItem.id === id) {
          return treeItem;
        } else {
          if (treeItem.children && treeItem.children.length > 0) {
            let res = _this.getTreeName(treeItem.children, id);
            if (res) {
              return res;
            }
          }
        }
      }
    },
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = this.getNode(node.children[i], str);
        }
      }
      return (str += node.id + ",");
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
      // 获取数据前设置好接口地址
      [CRUD.HOOK.beforeRefresh]() {
        return true
      }, // 新增与编辑前做的操作
      [CRUD.HOOK.afterToCU](crud, form) {
      },
      /**
       * 导出详情
       */
      toExportDetail(event) {
        this.crud.downloadDetailLoading = true
        this.crud.query.userIds = ''
        this.crud.selections.forEach(item => {
        this.crud.query.userIds += item.userId+ ','
        })
        const params = this.crud.getQueryParams()
        // if (event) {
        //   params.ids = event
        // } else {
        //   if (crud.selections) {
        //     params.ids = crud.selections.map(row => row.id).join()
        //   }
        // }
        download(this.crud.url + '/exportDetail', params).then(result => {
          downloadFile(result, this.crud.title + '数据', 'xlsx')
          this.crud.downloadDetailLoading = false
        }).catch(() => {
          this.crud.downloadDetailLoading = false
        })
      },
      //添加提交
      [CRUD.HOOK.afterValidateCU](crud) {
        if (crud.form.dataScope === '自定义' && crud.form.depts.length === 0) {
          this.$message({
            message: '自定义数据权限不能为空',
            type: 'warning'
          })
          return false
        } else if (crud.form.dataScope === '自定义') {
          const depts = []
          crud.form.depts.forEach(function (data, index) {
            const dept = {id: data}
            depts.push(dept)
          })
          crud.form.depts = depts
        } else {
          crud.form.depts = []
        }
        return true
      }
    }
  }
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
  .rightBox{
    .label{
      font-size: 25px;
    }
    .content{
      font-size: 19px;
    }
  }
</style>
